/*
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.common.shiro.filter;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.servlet.AdviceFilter;

import com.common.util.HtmlUtil;
import com.common.util.ResourceUtil;

/**
 * session 过期跳转
 * 
 * @author limk
 * @date 2018年2月12日 下午9:04:36
 * @version 1.0
 */
public class SessionAdviceFilter extends AdviceFilter {

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest rq = null;
        HttpServletResponse rp = null;
        rq = (HttpServletRequest) request;
        rp = (HttpServletResponse) response;
        
        if (!SecurityUtils.getSubject().isAuthenticated()) {
        	if(HtmlUtil.isFromRequest(rq)){
        		//在响应头设置session状态
        		rp.setHeader("sessionstatus", "timeout");
        	}
        	
        	if(HtmlUtil.isAjaxRequest(rq)) {
        		rp.setHeader("sessionstatus", "timeout");
        	}
        	
        	PrintWriter out = response.getWriter();    
            out.println("<html>");    
            out.println("<script>");    
            out.println("window.open ('" + ResourceUtil.getPorjectPath(rq) + "/login','_top')");    
            out.println("</script>");    
            out.println("</html>");    
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
        super.postHandle(request, response);
    }

    @Override
    public void afterCompletion(ServletRequest request, ServletResponse response, Exception exception)
            throws Exception {
        super.afterCompletion(request, response, exception);
    }

}